package com.xudow.app.ui.task;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import com.activeshare.edu.ucenter.common.messages.Message;
import com.activeshare.edu.ucenter.common.messages.order.PaymentMessage;
import com.activeshare.edu.ucenter.models.base.OrderPayments;
import com.activeshare.edu.ucenter.models.order.AgencyOrderItems;
import com.xudow.app.Config;
import com.xudow.app.XApplication;
import com.xudow.app.util.FileUtils;
import com.xudow.app.util.rest.XRestTemplate;

import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 增加订单支付信息 Task
 *
 * @author lukecheng
 */
public class PaymentCreateTask extends AsyncTask<HashMap<String, String>, Void, Void> {
    private static final String TAG = makeLogTag(PaymentCreateTask.class);

    private static final String PAYMENT_CREATE_URL = Config.BASE_URL + Config.PAYMENT_CREATE_URL;

    public static final int SUCCESS = 0;
    public static final int ERROR = 1;

    private Context context;
    private Handler handler;

    public PaymentCreateTask(Context context, Handler handler) {
        this.context = context;
        this.handler = handler;
    }

    private void sendErrorMessage(String msg) {
        android.os.Message message = new android.os.Message();
        message.what = ERROR;

        if (null != msg) {
            Bundle data = new Bundle();
            data.putString("errMessage", msg);
            message.setData(data);
        }

        handler.sendMessage(message);
    }

    private void sendSuccessMessage(PaymentMessage result) {
        android.os.Message message = new android.os.Message();
        message.what = SUCCESS;

        AgencyOrderItems[] items = new AgencyOrderItems[result.getOrderItems().size()];
        for (int i = 0; i < result.getOrderItems().size(); i++) {
            items[i] = result.getOrderItems().get(i);
        }

        Bundle data = new Bundle();
        data.putSerializable("payment", result.getPayment());
        data.putSerializable("orderItems", items);
        message.setData(data);

        handler.sendMessage(message);
    }

    @Override
    protected Void doInBackground(HashMap<String, String>... parameters) {
        XApplication application = (XApplication) context.getApplicationContext();

        XRestTemplate restTemplate = new XRestTemplate(application.getCookieStore(), context);
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        //restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        HashMap<String, String> param = parameters[0];

        MultiValueMap<String, String> valueMap = new LinkedMultiValueMap<String, String>();

        //order_id 订单编号 int
        if (param.get("order_id") != null) {
            valueMap.add("order_id", param.get("order_id"));
        }

        //pay_type 支付类型 int
        if (param.get("pay_type") != null) {
            valueMap.add("pay_type", param.get("pay_type"));
        }

        //pay_method 支付方式 int （如果pay_type是网上支付则需要返回）
        if (param.get("pay_method") != null) {
            valueMap.add("pay_method", param.get("pay_method"));
        }

        //pay_amount 付款数量 int
        if (param.get("pay_amount") != null) {
            valueMap.add("pay_amount", param.get("pay_amount"));
        }

        //coupon_id 优惠券id
        if (param.get("coupon_id") != null) {
            valueMap.add("coupon_id", param.get("coupon_id"));
        }

        //订单line item的id (用逗号隔开的字符串，例如：426,452)
        if (param.get("item_ids") != null) {
            valueMap.add("item_ids", param.get("item_ids"));
        }

        //用户针对每一个订单line item选择的课时 (用逗号隔开的字符串，例如：10,30)
        if (param.get("course_hours") != null) {
            valueMap.add("course_hours", param.get("course_hours"));
        }

        try {
            PaymentMessage result = restTemplate.postForObject(PAYMENT_CREATE_URL, valueMap,
                    PaymentMessage.class);
            /*String result = restTemplate.postForObject(PAYMENT_CREATE_URL, valueMap,
                    String.class);*/
            if (result != null) {
               /* LOGE("paymentmsg:",result);
                FileUtils.writeFile(result,new File(context.getCacheDir().getAbsolutePath(),"payment.txt"));*/
                if (result.getResult().equals("0")) {
                    sendSuccessMessage(result);
                } else if (result.getResult().equals("1")) {
                    sendErrorMessage(result.getErrorMessage());
                }
            } else {
                sendErrorMessage(null);
            }
        } catch (Exception e) {
            LOGE(TAG, e.getMessage());

            sendErrorMessage(e.getMessage());
        }

        return null;
    }
}
